#!/usr/bin/python
# -*- coding: UTF-8 -*-
from app import app
from functools import wraps
from flask import jsonify, request, current_app, Blueprint, abort
import time, datetime, os, random
# from flask_restful import reqparse, abort, Api, Resource
# from elasticsearch import Elasticsearch
from app.server import cu_mongodb_conn
from flask import make_response
from app.server.http_beta import add_headers
from app.user_manager import is_login
wikis = Blueprint('wikis', __name__)

# parser = reqparse.RequestParser()
# parser.add_argument('task')
# parser.add_argument('callback')

# app.config.from_object('config')
# host = app.config.get('ES_HOST')
# port = app.config.get('ES_PORT')
# es = Elasticsearch([{'host': host, 'port': port}])
create_wiki_id = lambda: 'wiki_' + str(round(time.time()*1000))

ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'gif', 'GIF'])

def support_jsonp(f):
    """Wraps JSONified output for JSONP"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        callback = request.args.get('callback', False)
        if callback:
            # content = str(callback) + '(' + str(f(*args,**kwargs).data) + ')'
            content = str(callback) + '(' + str(f(*args,**kwargs)) + ')'
            return current_app.response_class(content, mimetype='application/javascript')
        else:
            return f(*args, **kwargs)
    return decorated_function


def create_uuid():  # 生成唯一的图片的名称字符串，防止图片显示时的重名问题
    nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S");  # 生成当前时间
    randomNum = random.randint(0, 100);  # 生成的随机整数n，其中0<=n<=100
    if randomNum <= 10:
        randomNum = str(0) + str(randomNum);
    uniqueNum = str(nowTime) + str(randomNum);
    return uniqueNum;


def create_tag(wiki_id, tags):
    tag = tags.split(' ')
    print('tag:', tag)
    for t in tag:
        k = {"tag_code": t}
        res_tag = cu_mongodb_conn.find_one('tags', k)
        if not res_tag:
            value = {"tag_name": t, "tag_code": t, "tag_type": t, "create_time": datetime.datetime.utcnow()}
            cu_mongodb_conn.save('tags', value)
        wt_id = wiki_id + '_' + t
        k = {"_id": wt_id}
        res_wt = cu_mongodb_conn.find_one('tags', k)
        if not res_wt:
            value = {"_id": wt_id, "tag_name": t, "wiki_id": wiki_id, "create_time": datetime.datetime.utcnow()}
            cu_mongodb_conn.save('wiki_tag', value)


# 判断是否是OPTIONS请求
@app.before_request
def is_options():
    if request.method == 'OPTIONS':
        rst = make_response("ok")
        rst.headers['Access-Control-Allow-Origin'] = '*'
        rst.headers['Access-Control-Allow-Credentials'] = 'true'
        # rst.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
        allow_headers = "Referer,Accept,Origin,User-Agent,Content-Type"
        rst.headers['Access-Control-Allow-Headers'] = allow_headers
        abort(rst)
    else:
        pass


# 上传图片
@wikis.route('/uploadImg', methods=['POST'])
def upload_img():
    def allowed_file(filename):
        return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

    file_dir = app.config['UPLOAD_FOLDER']
    # if not os.path.exists(file_dir):
    #     os.makedirs(file_dir)
    f = request.files['photo']
    wiki_id = request.form.get('wiki_id')
    wiki_id = wiki_id if wiki_id else create_wiki_id()
    attached_name = request.form.get('name')
    if f and allowed_file(f.filename):
        fname = f.filename
        ext = fname.rsplit('.', 1)[1]
        new_filename = create_uuid() + '.' + ext
        attached_url = os.path.join(file_dir, new_filename)
        f.save(attached_url)
        wiki_attached = dict()
        wiki_attached['wiki_id'] = wiki_id
        wiki_attached['name'] = attached_name
        wiki_attached['attached_url'] = app.config['PREFIX_ATTACHED'] + new_filename
        wiki_attached['create_time'] = datetime.datetime.utcnow()
        cu_mongodb_conn.save('wiki_attached', wiki_attached)
        return add_headers(jsonify({"status": 0, "data": wiki_id}))
    else:
        return add_headers(jsonify({"status": 1, "data": "上传失败"}))


# 获取wiki附件
@wikis.route('/getWikiAttached/<wiki_id>', methods=['get'])
def get_atttached(wiki_id):
    p = dict()
    if wiki_id:
        p['wiki_id'] = wiki_id
    res = cu_mongodb_conn.find('wiki_attached', p)
    rows = []
    for k in res:
        row = dict()
        row['id'] = str(k['_id'])
        row['name'] = k['name']
        row['attached_url'] = k['attached_url']
        rows.append(row)
    resp = dict()
    resp['status'] = 0
    resp['data'] = rows
    return add_headers(jsonify(resp))


@wikis.route('/saveWiki', methods=['GET', 'POST'])
def save_wiki():
    if not is_login():
        resp = dict()
        resp['status'] = 1
        return add_headers(jsonify(resp)), 403
    data = request.get_json()
    # print(data)
    wiki = dict()
    wiki['_id'] = data['id'] if data['id'] else create_wiki_id()
    wiki['content'] = data['data']
    wiki['content_html'] = data['data_html']
    wiki['title'] = data['title']
    wiki['summary'] = data['summary']
    wiki['tags'] = data['tags']
    create_tag(wiki['_id'], wiki['tags'])
    wiki_info = dict()
    have_wiki = cu_mongodb_conn.find_one('wiki_info', {'_id': wiki['_id']})
    if have_wiki is None:  # is new wiki
        wiki_info['create_time'] = datetime.datetime.utcnow()
        wiki_info['read_num'] = 0
        wiki_info['last_time'] = datetime.datetime.utcnow()
    else:
        old_wiki = cu_mongodb_conn.find_one('wiki_content', {'_id': wiki['_id']})
        if old_wiki['content'] != wiki['content']:
            wiki_info['last_time'] = datetime.datetime.utcnow()
    cu_mongodb_conn.update_one('wiki_content', {'_id': wiki['_id']}, {'$set': wiki}, True)
    cu_mongodb_conn.update_one('wiki_info', {'_id': wiki['_id']}, {'$set': wiki_info}, True)
    resp = dict()
    resp['status'] = 0
    resp['data'] = wiki['_id']
    return add_headers(jsonify(resp)), 201


# 删除
@wikis.route('/delWiki/<wiki_id>', methods=['GET', 'POST'])
def del_wiki(wiki_id):
    wiki = dict()
    if wiki_id:
        wiki['_id'] = wiki_id
        wiki['offline'] = True
        wiki['last_time'] = datetime.datetime.utcnow()
    have_wiki = cu_mongodb_conn.find_one('wiki_info', {'_id': wiki['_id']})
    resp = dict()
    if have_wiki:
        cu_mongodb_conn.update_one('wiki_content', {'_id': wiki['_id']}, {'$set': wiki}, True)
        cu_mongodb_conn.update_one('wiki_info', {'_id': wiki['_id']}, {'$set': wiki}, True)
        resp['status'] = 0
        resp['data'] = wiki['_id']
    else:
        resp['status'] = 1
        resp['data'] = 'airball'
    return add_headers(jsonify(resp)), 201


@wikis.route('/getWiki/<wiki_id>', methods=['GET', 'POST'])
def get_wiki(wiki_id):
    p = dict()
    if wiki_id:
        p['_id'] = wiki_id
    res = cu_mongodb_conn.find_one('wiki_content', p)
    info = cu_mongodb_conn.find_one('wiki_info', p)
    resp = dict()
    if res and info:
        cu_mongodb_conn.update_one('wiki_info', p, {'$inc': {'read_num': 1}}, True)
        resp['status'] = 0
        res['last_time'] = info['last_time'].__format__('%Y-%m-%d')
        res['create_time'] = info['create_time'].__format__('%Y-%m-%d')
        res['read_num'] = info['read_num']
        resp['data'] = res
    else:
        resp['status'] = 1
        resp['data'] = 'airball'
    return add_headers(jsonify(resp))


@wikis.route('/getWikiList/<pageNum>', methods=['GET', 'POST'])
def get_wiki_list(pageNum):
    wiki_id = []
    if pageNum == '1':
        # 置顶部分
        k = {"tag": "mainpage"}
        res_top = cu_mongodb_conn.find('wiki_tag_top', k)
        for k in res_top:
            wiki_id.append(k['_id'])
        k_info = {'_id': {'$in': wiki_id}}
        rows = make_wiki_list(k_info)
    else:
        rows = []

    pageNum = int(pageNum) if pageNum else 1
    limit = 10
    k = {'$and': [{'_id': {'$nin': wiki_id}},
                  {'offline': {'$ne': True}}]}
    res = cu_mongodb_conn.find_many('wiki_info', k, 'last_time', -1, limit, (pageNum - 1) * limit)
    res_content = cu_mongodb_conn.find('wiki_content', k)
    wiki_content = dict()
    for k in res_content:
        wiki_content[k['_id']] = k
    for k in res:
        row = dict()
        row['id'] = k['_id']
        row['last_time'] = k['last_time'].__format__('%Y-%m-%d')
        row['read_num'] = k['read_num']
        # w = cu_mongodb_conn.find_one('wiki_content', {'_id':k['_id']})
        w = wiki_content[k['_id']]
        row['title'] = w['title']
        row['summary'] = w['summary']
        row['tags'] = w['tags']
        rows.append(row)
    resp = dict()
    resp['status'] = 0
    resp['data'] = rows
    return add_headers(jsonify(resp))


# 检索
@wikis.route('/searchWikiList/<pageNum>/<keyword>', methods=['GET', 'POST'])
def search_wiki_list(pageNum, keyword):
    k = {'$and': [{'offline': {'$ne': True}},
                  {'$or': [{'content': {'$regex': keyword, '$options': "si"}},
                           {'title': {'$regex': keyword, '$options': "si"}},
                           {'summary': {'$regex': keyword, '$options': "si"}}]
                   }
                  ]
         }
    # k = {'$or': [{'content': {'$regex': keyword, '$options': "si"}}, {'title': {'$regex': keyword, '$options': "si"}},
    #              {'summary': {'$regex': keyword, '$options': "si"}}]}
    pageNum = int(pageNum) if pageNum else 1
    limit = 10
    res_search = cu_mongodb_conn.find_many('wiki_content', k, 'last_time', -1, limit, (pageNum - 1) * limit)
    wiki_id = []
    for k in res_search:
        wiki_id.append(k['_id'])
    k_info = {'_id': {'$in': wiki_id}}
    # res = cu_mongodb_conn.find_many('wiki_info', k_info, 'last_time', -1)
    # res_content = cu_mongodb_conn.find('wiki_content', k_info)
    # wiki_content = dict()
    # for k in res_content:
    #     wiki_content[k['_id']] = k
    # rows = []
    # for k in res:
    #     row = dict()
    #     # for key, value in k.items():
    #     #     row[key] = value
    #     row['id'] = k['_id']
    #     row['last_time'] = k['last_time'].__format__('%Y-%m-%d')
    #     row['read_num'] = k['read_num']
    #     # w = cu_mongodb_conn.find_one('wiki_content', {'_id': k['_id']})
    #     w = wiki_content[k['_id']]
    #     row['title'] = w['title']
    #     row['summary'] = w['summary']
    #     rows.append(row)
    rows = make_wiki_list(k_info)
    resp = dict()
    resp['status'] = 0
    resp['data'] = rows
    return add_headers(jsonify(resp))


# 推荐列表
@wikis.route('/getRecommendList/<pageNum>', methods=['GET', 'POST'])
def recommend_wiki_list(pageNum):
    k = {}
    res_re = cu_mongodb_conn.find('wiki_recommend', k)
    wiki_id = []
    for k in res_re:
        wiki_id.append(k['_id'])
    k_info = {'_id': {'$in': wiki_id}}
    # res = cu_mongodb_conn.find_many('wiki_info', k_info, 'last_time', -1)
    # res_content = cu_mongodb_conn.find('wiki_content', k_info)
    # wiki_content = dict()
    # for k in res_content:
    #     wiki_content[k['_id']] = k
    # rows = []
    # for k in res:
    #     row = dict()
    #     row['id'] = k['_id']
    #     row['last_time'] = k['last_time'].__format__('%Y-%m-%d')
    #     row['read_num'] = k['read_num']
    #     # w = cu_mongodb_conn.find_one('wiki_content', {'_id': k['_id']})
    #     w = wiki_content[k['_id']]
    #     row['title'] = w['title']
    #     row['summary'] = w['summary']
    #     rows.append(row)
    rows = make_wiki_list(k_info)
    resp = dict()
    resp['status'] = 0
    resp['data'] = rows
    return add_headers(jsonify(resp))


# 谚语列表
@wikis.route('/getProverbList/<pageNum>', methods=['GET', 'POST'])
def proverb_wiki_list(pageNum):
    pageNum = int(pageNum) if pageNum else 1
    limit = 10
    k = {"tag_name": {"$in": ["谚语", "语录"]}}
    res_re = cu_mongodb_conn.find_many('wiki_tag', k, 'create_time', -1, limit, (pageNum - 1) * limit)
    wiki_id = []
    for k in res_re:
        wiki_id.append(k['wiki_id'])
    k_info = {'_id': {'$in': wiki_id}}
    rows = make_wiki_list(k_info)
    resp = dict()
    resp['status'] = 0
    resp['data'] = rows
    return add_headers(jsonify(resp))


# 板块列表
@wikis.route('/getPlateList/<plate>/<pageNum>', methods=['GET', 'POST'])
def plate_wiki_list(plate, pageNum):
    pageNum = int(pageNum) if pageNum else 1
    limit = 10
    #  板块
    if plate == 'Proverb':
        k = {"tag_name": {"$in": ["谚语", "语录"]}}
        k_top = {"tag": "Proverb"}
    elif plate == 'other':
        k = {"tag_name": {"$in": ["other"]}}
    else:
        k = {}
        k_top = {"tag": "none"}
    # 置顶部分
    res_top = cu_mongodb_conn.find('wiki_tag_top', k_top)
    wiki_top_wiki_id = []
    for k in res_top:
        wiki_top_wiki_id.append(k['_id'])
    wiki_top_k = {'_id': {'$in': wiki_top_wiki_id}}
    rows_base = make_wiki_list(wiki_top_k)
    # 置顶结束
    res_tags = cu_mongodb_conn.find_many('wiki_tag', k, 'create_time', -1, limit, (pageNum - 1) * limit)
    wiki_tags_wiki_id = []
    for k in res_tags:
        wiki_tags_wiki_id.append(k['wiki_id'])
    wiki_tags_k = {'_id': {'$in': wiki_tags_wiki_id}}
    rows_tags = make_wiki_list(wiki_tags_k)
    rows_base.extend(rows_tags)
    resp = dict()
    resp['status'] = 0
    resp['data'] = rows_base
    return add_headers(jsonify(resp))


# 组装返回数据集
def make_wiki_list(k_info):
    # wiki_id = []
    # for k in res:
    #     wiki_id.append(k['_id'])
    # k_info = {'_id': {'$in': wiki_id}}
    res = cu_mongodb_conn.find_many('wiki_info', k_info, 'last_time', -1)
    res_content = cu_mongodb_conn.find('wiki_content', k_info)
    wiki_content = dict()
    for k in res_content:
        wiki_content[k['_id']] = k
    rows = []
    for k in res:
        row = dict()
        row['id'] = k['_id']
        row['last_time'] = k['last_time'].__format__('%Y-%m-%d')
        row['read_num'] = k['read_num']
        w = wiki_content[k['_id']]
        row['title'] = w['title']
        row['summary'] = w['summary']
        row['tags'] = w['tags']
        rows.append(row)
    return rows


@wikis.route('/getTags/', methods=['GET', 'POST'])
def get_tags():
    # 全部
    k = {}
    res_tags = cu_mongodb_conn.find('tags', k)
    rows = []
    for k in res_tags:
        rows.append(k['tag_code'])
    resp = dict()
    resp['status'] = 0
    resp['data'] = rows
    return add_headers(jsonify(resp))